package com.gegewa.topic.algorithm;

public class QuickSort {

    public static void main(String[] args) {
        int[] data = new int[] {5, 6, 2, 0, 5};
        sortBySwapOneAtATime(data, 0, 4);
        for (int i = 0, size = data.length; i < size; i++) {
            System.out.println(data[i]);
        }
    }

    /**
     * 一次交换一个数的排序
     */
    public static void sortBySwapOneAtATime(int[] data, int left, int right) {
        if (left >= right) {
            return;
        }
        int i = left, j = right, baseNumber = data[left];
        while (i != j) {
            while (data[j] >= baseNumber && i < j) {
                j--;
            }
            if (i < j) {
                data[i] = data[j];
                i++;
            }
            while (data[i] <= baseNumber && i < j) {
                i++;
            }
            if (i < j) {
                data[j] = data[i];
                j--;
            }
        }
        data[i] = baseNumber;
        sortBySwapOneAtATime(data, left, i - 1);
        sortBySwapOneAtATime(data, i + 1, right);
    }

    /**
     * 一次交换两个数的排序
     */
    public static void sortBySwapTwoAtATime(int[] data, int left, int right) {
        if (left >= right) {
            return;
        }
        int i = left, j = right, temp;
        while (i != j) {
            while (data[j] >= data[left] && i < j) {
                j--;
            }
            while (data[i] <= data[left] && i < j) {
                i++;
            }
            if (i < j) {
                temp = data[i];
                data[i] = data[j];
                data[j] = temp;
            }
        }
        temp = data[left];
        data[left] = data[i];
        data[i] = temp;

        sortBySwapTwoAtATime(data, left, i - 1);
        sortBySwapTwoAtATime(data, i + 1, right);
    }

}
